<?php
declare (strict_types = 1);

namespace app\index\controller;

// use think\Request;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Config;
use app\middleware\Auth;

class Activity{
    
    protected $middleware = [Auth::class];
    //获取列表
    public function list(){
        if(Request::isPost()){
            $page=input('param.page',1);
            $size=input('param.size',10);
            $where=[];

            $where[]=['is_publish','=',1];
            $data=Db::table('activity')->field('id,title,cover,start_time,end_time,fee,is_publish,profile')
            ->where($where)->order('id desc')
            ->paginate([
                    'list_rows' => $size,
                    'page'      => $page
                ]);
    
            $total=$data->total();
            $data=$data->items();
            $page_count=ceil($total/$size);
            foreach($data as $k=>$v){
                $cover=json_decode($v['cover'],true);
                $data[$k]['cover']=isset($cover[0])?'https://darong.storage.1415926.com.cn'.$cover[0]:'https://uviewui.com/swiper/swiper1.png';
            }
            $result=['code'=>200,'message'=>'获取成功','success'=>true,'result'=>['list'=>$data,'total'=>$total,'page'=>['current'=>$page,'size'=>$size,'total'=>$page_count]]];
            return json($result);
        }
    }

    //通过Id获取展品信息
    public function getDetailById(){
        if(Request::isPost()){
            $id=input('param.id',0);
            if($id==0){
                return json(['code'=>200,'success'=>false,'message'=>'参数出错']);
            }
            $data=$this->getActivityById($id);
            // $data['isOpeningApply']=0;//是否开启预约
            $data['isOpeningApply']=$data['is_booking']==1&&$data['end_time']>time()?true:false;
            $data['isShowFee']=0;
            $dateRange=($data['end_time']-$data['start_time'])/86400;
            $data['date']['range']=[];
            $data['date']['list']=[];
            $weekdayNames = ['周一','周二','周三','周四','周五','周六','周日'];
            $openId=input('param.openId','');
            $data['account']=[];
            $apply=[];
            if($openId!=''){
                $data['account']=Db::table('account')->field('account_id,openid,mobile,nickname,avatar,true_name')
                ->where(['openid'=>$openId])->find();
                $apply=Db::table('apply')->where(['activity_id'=>$id,'openid'=>$openId])->column('booking_date');
            }
            if($dateRange>1){
                for($i=0;$i<$dateRange;$i++){
                    $data['date']['list'][]=['day'=>date('Y-m-d',strtotime("+$i days",$data['start_time'])),
                    'weekday'=> $weekdayNames[date('w', strtotime("+$i days",$data['start_time']))],
                    'isApply'=>in_array(date('Y-m-d',strtotime("+$i days",$data['start_time'])),$apply)];
                }
            }else{
                array_push($data['date']['list'],['day'=>date('Y-m-d',$data['start_time']),
                 'weekday'=> $weekdayNames[date('w', strtotime("+0 days",$data['start_time']))],
                 'isApply'=>in_array(date('Y-m-d',strtotime("+0 days",$data['start_time'])),$apply)
                ]);
            }
            
            // if($dateRange>1){
            //     for($i=0;$i<$dateRange;$i++){
            //         // $data['date']['range'][]=date('Y-m-d',strtotime("+$i days",$data['start_time']));
            //         $data['date']['list'][]=['day'=>date('Y-m-d',strtotime("+$i days",$data['start_time'])),
            //         'weekday'=> $weekdayNames[date('w', strtotime("+$i days",$data['start_time']))]];
            //     }
            // }else{
            //     // array_push($data['date']['range'],date('Y-m-d',strtotime("+1 days",$data['start_time'])));
            //     // array_push($data['date']['range'],date('Y-m-d',strtotime($data['start_time'])));
            //     array_push($data['date']['list'],['day'=>date('Y-m-d',$data['start_time']),
            //      'weekday'=> $weekdayNames[date('w', strtotime("+0 days",$data['start_time']))]
            //     ]);
            // }
            // //  $data['date']['default']=$data['date']['range'][0];
            // $openId=input('param.openId','');
            // $data['account']=[];
            // if($openId!=''){
            //     $data['account']=Db::table('account')->field('account_id,openid,mobile,nickname,avatar,true_name')
            //     ->where(['openid'=>$openId])->find();
            // }
            return json(['code'=>200,'success'=>true,'message'=>'获取成功','result'=>$data]);
        }
    }

    function getActivityById($id){
        $redis=\think\facade\Cache::store('redis')->get('ACTIVITY_'.$id);
        $data=json_decode(json_encode($redis),true);
        if(!$data){
            $data=Db::table('activity')->field('id,title,cover,start_time,end_time,fee,is_publish,profile,is_booking')
            ->where(['id'=>$id])->find();
            $data['startTime']=date('Y-m-d',$data['start_time']);
            $data['endTime']=date('Y-m-d',$data['end_time']);
            if($data['cover']){
                $data['cover']=json_decode($data['cover'],true);
                foreach($data['cover'] as $k=>$v){
                    $data['cover'][$k]='https://darong.storage.1415926.com.cn'.$v;
                }
            }else{
                $data['cover']=[];
            }
            $data['status']=['text'=>'预热中','type'=>'primary','plain'=>true];
            if($data['start_time']<time()&&$data['end_time']>time()){
                $data['status']=['text'=>'进行中','type'=>'primary','plain'=>false];
            }
            if($data['end_time']<time()){
                $data['status']=['text'=>'已结束','type'=>'error','plain'=>false];
            }
            \think\facade\Cache::store('redis')->set('ACTIVITY_'.$id,$data,600);
        }
        return $data;
    }
    
    
    public function bookingApply(){
        if(Request::isPost()){
            // $param=input('param.');
            try{
                $param=input('post.');
                \think\facade\Log::info("/index/Activity/bookingApply 报名请求：".json_encode(input('param.'),JSON_UNESCAPED_UNICODE));
                $paramArray=['openId','accountId','activityId','mobile','date','name'];
                foreach($paramArray as $v){
                    if(!isset($param[$v])||$param[$v]==''){
                        \think\facade\Log::info("/index/Activity/bookingApply 报名失败结果：参数{$v}缺失");
                        return json(['code'=>200,'success'=>false,'message'=>'参数缺失']);
                    }
                }
                $isExist=Db::table('apply')->where(['openid'=>$param['openId'],'activity_id'=>$param['activityId'],'booking_date'=>$param['date']])->count();
                if($isExist>0){
                    \think\facade\Log::info("/index/Activity/bookingApply 你已报名，请勿重复提交：参数{$isExist}缺失");
                    return json(['code'=>200,'success'=>false,'message'=>'你已报名，请勿重复提交']);
                }
                $applyId=Db::table('apply')->insertGetId([
                    'activity_id'=>$param['activityId'],
                    'account_id'=>$param['accountId'],
                    'openid'=>$param['openId'],
                    'true_name'=>$param['name'],
                    'nickname'=>$param['nickname'],
                    'booking_date'=>$param['date'],
                    'mobile'=>$param['mobile'],
                    'accompany'=>$param['accompany'],
                    'remark'=>$param['remark'],
                    'create_at'=>time()
                ]);
                Db::table('account')->where(['openid'=>$param['openId']])->update(['true_name'=>$param['name']]);
                return json(['code'=>200,'success'=>true,'message'=>'报名成功','result'=>['applyId'=>$applyId]]);

            }catch(Exception $e){
                \think\facade\Log::info("/index/Exhibits/getExhibitById 报名失败结果：".$e->getMessage());
                return json(['code'=>200,'success'=>false,'message'=>$e->getMessage()]);
            }
        }
    }
}